import React from 'react'
import {withRouter,} from 'react-router-dom'
import './topic-detail.css'
import {connect,} from 'react-redux'
import LocalStorageService from "../../utils/LocalStorageService";
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import DefaultAvatar from "../../res/images/web/shared/缺省头像.png"
import LvMark from "../../shared-components/LvMark/LvMark";
import {Modal, Toast} from "antd-mobile";
import CommentItem from "./CommentItem/CommentItem";
import VipIcon from "../../res/images/web/my/vip kim@2x.png";
import {GlobalStore} from "../../context";
import HomeContainer from "../home/home";

class TopicDetail extends React.Component {
    constructor(props) {
        super(props)
        this.id = Number(this.props.match.params.topicId)
        this.uid = LocalStorageService.get('userid')
        this.storage = LocalStorageService
        this.end = this.props.topic.topicDetail.end
        this.state = {
            p: 0,
            txt: '',
            comment: '',
            viewType: 0,
        }
    }

    componentDidMount() {
        this.getUser()
        this.getTopic()
        this.getComments()
    }

    componentWillUnmount() {
        this.emptyComments()
        this.emptyTopicDetail()
    }

    onChange = (e, type) => {
        const v = e.target.value
        this.setState({
            [type]: v,
        })
    }

    getUser = () => {
        const uid = LocalStorageService.get('userid')
        const userDetail = this.props.user.userdetail
        const login = LocalStorageService.get('isLogin')
        const flag = userDetail.initFlag
        if (flag === 0 && login) {
            this.props.fetchUserDetail({uid,})
        }
    }

    getTopic = () => {
        const id = this.id
        this.props.doGetTopicDetail({id,})
    }

    getComments = () => {
        const p = this.state.p
        const cid = 1
        const huatiid = this.id
        const viewType = this.state.viewType
        const uid = this.uid
        const params = {
            p,
            cid,
            huatiid,
            uid,
        }
        if (viewType === 1) {
            params.lzuid = this.props.topic.topicDetail.content.Uid
        }
        this.props.doGetComment(params)
    }

    empty = () => {
        this.setState({
            txt: '',
        })
    }

    emptyTopicDetail = () => {
        this.props.doEmptyTopicDetail()
    }

    emptyComments = () => {
        this.props.doEmptyTopicDetailComments()
    }

    checkBeforeCommit = () => {
        const isLogin = this.storage.get('isLogin')
        return isLogin

        const detail = this.props.user.userdetail
        const {
            Viplevel,
            Vip,
        } = detail
        if (!isLogin) return false
        if (Vip > 0) return true
        return Viplevel >= 5
    }

    alert = () => {
        const btnList = [
            {text: '知道了', onPress: () => {}},
            // {text: <span>如何升级</span>, onPress: () => {this.props.history.push('../userinfo/level')}},
            {text: <span>登陆</span>, onPress: () => {this.props.history.push('../../login')}},
        ]
        // Modal.alert('等级需到达5级以上或者会员才可以互动', '', btnList)
        Modal.alert('只有会员才可以互动', '', btnList)
    }

    comment = (data) => {
        const allow = this.checkBeforeCommit()
        if (!allow) {
            this.alert()
            return
        }
        const params = {
            uid: this.uid,
            huatiid: this.id,
            commentid: data.commentid,
            txt: data.commentid > -1 ? this.state.comment : this.state.txt,
            zan: 0,
            huatiuid: data.huatiuid,
        }
        const resp = this.props.doComment(params)
        resp.then(resp => {
            const data = resp.data
            if (data.ok) {

                Toast.info('回复成功', 1)
                setTimeout(() => {
                    this.getTopic()
                    this.emptyComments()
                    this.setState({
                        p: 0,
                    }, () => {
                        this.getComments()
                        this.empty()
                    })
                }, 1000)
            }
            if (data.err === 50008) {
                Toast.fail(`包含${data.data}`, 1)
            }
        })
    }

    zan = (data) => {
        const allow = this.checkBeforeCommit()
        if (!allow) {
            this.alert()
            return
        }
        const did = data.did
        if (did > 0) {
            Toast.info('你已经赞过啦')
            return
        }

        const params = {
            uid: this.uid,
            huatiid: this.id,
            commentid: data.commentid,
            txt: '',
            zan: 1,
        }

        this.props.doComment(params)
            .then((resp) => {
                if (resp.data.ok) {
                    Toast.info('点赞成功')
                    this.addZan(params)
                }
            })

    }

    report = (comment) => {
        const allow = this.checkBeforeCommit()
        if (!allow) {
            this.alert()
            return
        }
        const uid = this.uid
        const huatiid = comment.Htid
        const commentid = comment.Id

        this.props.doReportComment({uid, huatiid, commentid,})
    }

    addZan = (params) => {
        const allow = this.checkBeforeCommit()
        if (!allow) {
            this.alert()
            return
        }
        this.props.doAddZan(params)
    }

    reply = (c, i) => {
        const allow = this.checkBeforeCommit()
        if (!allow) {
            this.alert()
            return
        }
        const topicId = this.id
        const viewType = this.state.viewType
        const pushState = {index: i, comment: c,}
        if (viewType === 1) {
            pushState.lzuid = this.props.topic.topicDetail.content.Uid
        }

        this.props.history.push(`${topicId}/${c.Id}`, pushState)
    }

    formatDate = (date) => {
        if (date) {
            const o = new Date(date * 1000)
            const arr = o.toLocaleDateString().split('/')
            let m = String(arr[1])
            if (m.length === 1) m = '0' + m
            const d= arr[2]
            // const md = o.toLocaleDateString().split('/').slice(1).join('/')
            const time = o.toTimeString().split(' ')[0].slice(0, 5)
            const result = `${m}月${d}日 ${time}`
            return result
        }
        return ''
    }

    switchViewType = () => {
        const viewType = this.state.viewType

        // if (viewType === type) return
        this.setState({
            p: 0,
            viewType: viewType === 0 ? 1 : 0,
        }, () => {
            this.emptyComments()
            this.getComments()
        })

    }

    onTouchEnd = e => {

        const ctn = this.listCtn
        const last = ctn.lastElementChild
        const rect = last.getBoundingClientRect()
        const cH = document.documentElement.clientHeight
        const bottom = rect.bottom

        const end = this.props.topic.topicDetail.end
        if (cH > bottom - 50 && !end) {
            this.setState({
                p: this.state.p + 1
            }, () => {
                this.getComments()
            })
        }
    }

    goBack = () => {
        this.context.topic.setFromTopic()
        this.props.history.goBack()
    }

    render() {

        const history = this.props.history
        const title = '足球话题讨论区'
        const detail = this.props.topic.topicDetail
        const commentsObj = detail.comments
        let comments = []
        if (commentsObj !== {}) {
            if (commentsObj) {
                const ps = Object.keys(commentsObj)

                // eslint-disable-next-line array-callback-return
                ps.map(p => {
                    const arr = commentsObj[p]
                    arr.forEach(c => c.p = p)
                    comments.push(...commentsObj[p])
                })
            }

        }
        const content = detail.content
        const viewType = this.state.viewType

        const {
            // Uid: uid,
            Username: userName,
            Avatar: avatarUrl,
            Lv: lv,
            Title: topicTitle,
            Txt: topicTxt,
            Img,
            // Jing: JH,
            Createt: createAt,
            Comment,
            Clock: lock,
            // Username: "18205964188"
            // Avatar: ""
            // Lv: 5
            // Title: "话题1"
            // Txt: "话题1"
            // Img: "["http://test.youtoball.com/huati/20200410113012.1.jpg"]"
            //     Comment: 2
            // Jing: 0
            // Createt: 1586489412
            // Commentt: 1586489532
            // Ding: 0
            // Dingt: 0
            // Jingt: 0
            Vip,
        } = content
        const isVip = Vip > 0


        let imgList = []
        if (Img && Img !== '') {
            imgList = JSON.parse(Img)
        }

        const vipIcon = <img alt='' src={VipIcon} style={{width: '37px', marginRight: '4px',}}/>

        const contentTemplate = <div
            className='topic-detail-ctn'
        >

            <div
                className='flex-align-center topic-detail-head'
            >
                <img
                    src={avatarUrl ? avatarUrl : DefaultAvatar}
                    alt=''
                    className='topic-detail-avatar'
                />
                <div>
                    <div
                        className='flex-align-center'
                        style={{
                            margin: '4px',
                        }}
                    >
                        <p
                            className='topic-detail-host-name'
                            style={{
                                color: isVip ? 'rgb(250, 114, 104)' : '',
                            }}
                        >{userName ? userName : ''}</p>
                        {isVip ? vipIcon : null}
                        <LvMark lv={lv}/>
                    </div>
                    <p
                        className='topic-detail-time'
                        style={{
                            fontSize: '10px',
                            lineHeight: '10px',
                            color: 'rgba(158,158,158,1)',
                            margin: '4px'
                        }}
                    >
                        {this.formatDate(createAt)}
                    </p>
                </div>

            </div>

            <h3 className='topic-detail-title'>{topicTitle}</h3>

            <p className='topic-detail-content'>{topicTxt}</p>

            <div className='topic-detail-imgs'>
                {imgList.map(img => <img alt='' src={img} key={img}/>)}
            </div>

        </div>

        const lockInput = <div className='topic-detail-bottom-input'>
            <div className='lock-input'>
                <span>该帖已锁定，暂不能回复</span>
            </div>
            <div className='lock-btn'>
                发送
            </div>
        </div>


        const input = <div className='topic-detail-bottom-input'>
            <input
                value={this.state.txt}
                placeholder='回复楼主...'
                onChange={(e) => this.onChange(e, 'txt')}
            />

            <div
                className='unlock-btn'
                onClick={(e) => this.comment({commentid: -1, huatiuid: content.Uid})}
            >发送</div>
        </div>

        const gap = <div
            className='flex-space-between-align-center'
            style={{
                height: '46px',
                padding: '16px',
                boxSizing: 'border-box'
            }}
        >
            <p>全部回复 {Comment}</p>
            <div
                className='flex-space-between-align-center'
            >
                <div
                    onClick={(e) => this.switchViewType()}
                    className={`topic-detail-btn${viewType === 1 ? ' topic-detail-btn-active' : ''}`}
                >
                    <span>只看楼主</span>
                </div>
                {/*<div*/}
                {/*    // onClick={(e) => this.switchViewType(0)}*/}
                {/*    // className={`topic-detail-btn${viewType === 0 ? ' topic-detail-btn-active' : ''}`}*/}
                {/*    className='topic-detail-btn topic-detail-btn-active'*/}
                {/*>*/}
                {/*    <span>最早回复</span>*/}
                {/*</div>*/}
            </div>
        </div>

        const commentList = comments.map((c, i) => {
            let end = c.end

            return <CommentItem
                comment={c}
                end={end}
                key={i}
                index={i}
                onReply={this.reply}
                onReport={() => this.report(c)}
                onZan={() => this.zan({did: c.Zan, commentid: c.Id,})}
                level={1}
            />
        })

        const emptyBottom = <div style={{textAlign: 'center', marginTop: '24px',}}>
            <span className='gray-text'>还没有回帖，快来抢沙发～</span>
        </div>

        const moreBottom = <div style={{textAlign: 'center', marginTop: '24px',}}>
            <span className='gray-text'>下滑加载更多～</span>
        </div>

        const endBottom = <div style={{textAlign: 'center', marginTop: '24px',}}>
            <span className='gray-text'>全部加载完毕啦～</span>
        </div>
        let bottom = null
        let end = this.props.topic.topicDetail.end
        if (comments.length === 0) {
            bottom = emptyBottom
        } else {
            // if
            if (end) {
                bottom = endBottom
            } else {
                bottom = moreBottom
            }
        }

        return <GoBackLayout
            title={title}
            history={history}
            onLeftClick={() => this.goBack()}

        >

            <div
                style={{paddingBottom: '50px',}}
            >
                {contentTemplate}
                {lock ? lockInput : input}
                {/*{lock ? null : gap}*/}
                {gap}
                {lock ? null : <div
                    onTouchEnd={e => this.onTouchEnd(e)}
                    ref={el => this.listCtn = el}
                >
                    {commentList}
                </div>}
                {bottom}
            </div>

        </GoBackLayout>

    }
}

const mapState = state => ({
    topic: state.topic,
    user: state.user,
})

const mapDispatch = dispatch => ({
    doGetTopicDetail: (payload) => dispatch.topic.doGetTopicDetail(payload),
    doGetComment: (payload) => dispatch.topic.doGetComment(payload),
    doComment: (payload) => dispatch.topic.doComment(payload),
    doZanComment: (payload) => dispatch.topic.doZanComment(payload),
    doEmptyTopicDetail: (payload) => dispatch.topic.doEmptyTopicDetail(payload),
    doEmptyTopicDetailComments: (payload) => dispatch.topic.doEmptyTopicDetailComments(payload),
    fetchUserDetail: (payload) => dispatch.user.fetchUserDetail(payload),
    doAddZan: (payload) => dispatch.topic.doAddZan(payload),
    doReportComment: (payload) => dispatch.topic.doReportComment(payload),
})

TopicDetail.contextType = GlobalStore

export default connect(mapState, mapDispatch)(withRouter(TopicDetail))
